import 'dart:async';
import 'dart:convert';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/ui/index/even/location_changed_event.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'service/amap_service.dart';

///高德地图控制
class AmapRepository {
  static AmapRepository _instance;

  ///关于地图api调用
  AmapService _amapService;

  AmapService get amapServive => _amapService;

  AmapRepository._();

  static AmapRepository getInstance() {
    if (_instance == null) {
      _instance = new AmapRepository._();
    }
    return _instance;
  }

  init([VoidCallback locationSuccessCallback]) async {
    AMapFlutterLocation.setApiKey(ConstantRepository.of().getAmapAndroidKey(), ConstantRepository.of().getAmapIOSKey());
    _amapService ??= AmapService();

    // // 很奇怪，每次第一次打开app进到某一个页面并不会定位，第二次才会定位，默认初始化的时候定位一下，时间紧急先这么处理吧
    // VgLocation vgLocation = VgLocation();
    // VgLocation().requestSingleLocation((value) {
    //   vgLocation.dispose();
    //   if (locationSuccessCallback != null) locationSuccessCallback();
    // });
  }

}


class VgLocation {
  AMapFlutterLocation _locationPlugin = AMapFlutterLocation();
  StreamSubscription<Map<String, Object>> _locationListener;

  void requestSingleLocation(ValueChanged<Map<String, Object>> locationMap) async {
    if (await checkPermission() == false) {
      return;
    }
    AMapLocationOption options = AMapLocationOption(onceLocation: true);
    _locationPlugin.setLocationOption(options);
    _locationListener = _locationPlugin.onLocationChanged().listen(locationMap);
    _locationListener.onData((data) {
      //发送位置信息更新的通知
      if(data.containsKey("latitude") && data.containsKey("longitude")){
        LatLngBean latLngBean = LatLngBean.fromMap(data);
        String gps = latLngBean.latitude.toString() + "," + latLngBean.longitude.toString();
        VgEventBus.global.send(new LocationChangedEvent(gps,latLngBean));
      }
      VgLocationUtils.transLocationToLatLngAndCache(data);
      locationMap.call(data);
    });
    _locationPlugin.startLocation();
    Future.delayed(Duration(seconds: 20), () {
      if (_locationPlugin != null) _locationPlugin.stopLocation();
    });
  }

  void requestSingleLocationWithoutCheckPermission(ValueChanged<Map<String, Object>> locationMap) async {
    AMapLocationOption options = AMapLocationOption(onceLocation: true);
    _locationPlugin.setLocationOption(options);
    _locationListener = _locationPlugin.onLocationChanged().listen(locationMap);
    _locationListener.onData((data) {
      //发送位置信息更新的通知
      if(data.containsKey("latitude") && data.containsKey("longitude")){
        LatLngBean latLngBean = LatLngBean.fromMap(data);
        String gps = latLngBean.latitude.toString() + "," + latLngBean.longitude.toString();
        VgEventBus.global.send(new LocationChangedEvent(gps,latLngBean));
      }
      VgLocationUtils.transLocationToLatLngAndCache(data);
      locationMap.call(data);
    });
    _locationPlugin.startLocation();
    Future.delayed(Duration(seconds: 20), () {
      if (_locationPlugin != null) _locationPlugin.stopLocation();
    });
  }

  ///检查权限
  Future<bool> checkPermission() async {
    String permissResult = await PermissionUtil().requestLocation();
    if (StringUtils.isNotEmpty(permissResult)) {
      // VgEventBus.global.send(ToastEven(msg: permissResult));
      return false;
    }
    return true;
  }

  void dispose() {
    if (_locationListener != null) {
      _locationListener.cancel();
    }
    if (_locationPlugin != null) {
      _locationPlugin.destroy();
    }
  }
}
